<template>
  <el-form class="login-form"

           ref="ruleFormRef"
           :model="loginRequest"
           :rules="determineFormRules()">
    <h1>Hello!</h1>
    <h2>
      <div>欢迎来到硅谷甄选!</div>
      <el-row justify="space-evenly" style="flex: 1;margin-top: 10px" >
        <el-button type="info" :text="loginRequest.loginType!=='user_pass'"  @click="changeLoginType('user_pass')" :icon="Lock">密码登陆</el-button>
        <el-button type="info" :text="loginRequest.loginType!=='email_code'"  @click="changeLoginType('email_code')" :icon="Message">邮箱登陆</el-button>
        <el-button type="info" :text="loginRequest.loginType!=='mobile_code'"  @click="changeLoginType('mobile_code')" :icon="Cellphone">手机号登陆</el-button>
      </el-row>
    </h2>
    <div class="item-list">

      <component :is="componentSwitch[loginRequest.loginType]" :login-request="loginRequest" @sendEmail="doSendEmail" @sendMobileCode="doSendMobileCode"></component>


      <el-form-item>
        <el-row justify="space-between" style="flex: 1">
          <el-button type="primary" :loading="isLogining" class="login-htn" @click="submitForm(ruleFormRef)">登录</el-button>
          <el-button type="warning" class="login-htn" @click="resetForm(ruleFormRef)">重置</el-button>
        </el-row>
      </el-form-item>


      <el-form-item>

      </el-form-item>
    </div>
  </el-form>
</template>

<script setup>

import { User, Lock,Message,Cellphone} from '@element-plus/icons-vue'
import { reactive ,ref } from 'vue';

import useUserStore from '@/store/modules/user'

import {ElMessage, ElNotification} from "element-plus";

import {useRoute, useRouter} from "vue-router";
import {getDate} from "@/api/util/dateutil.js";
import userRouteStore from "@/store/modules/route.js";
import {sendEmailCode,sendMobileCode} from "@/api/backend/auth/index.js";


let loginRequest=reactive({username:"",password:"",loginType:"user_pass",email:'',code:'',phone:''})

const changeLoginType=(type)=>{
  console.log(type)
  loginRequest.loginType=type
}
const $router=useRouter()
const $route=useRoute()
const redirect=$route.query.redirect
const store=useUserStore()
const routeStore=userRouteStore()
const isLogining= ref(false)

const componentSwitch=reactive({
  user_pass:'UserPassItem',
  email_code:'EmailCodeItem',
  mobile_code:'MobileCodeItem'
})
const doSendEmail=()=>{
  sendEmailCode(loginRequest.email).then(res=>{

  }).catch(err => {
    console.log(err)
  })
}

const doSendMobileCode=()=>{
  sendMobileCode(loginRequest.phone).then(res=>{})
      .catch(err => {
        console.log(err)
      })
}
function doLogin(){

  isLogining.value=true

  store.userLogin(loginRequest)
      .then(res=>{
        isLogining.value=false
        ElMessage({
          type:"success",
          message: '登录成功',
          duration: 3000,
        })

        routeStore.clear()

        $router.push(redirect||'/').then(res=>{
          ElNotification({
            title:`${getDate()}好! ${store.userInfo.realname}`,
            message:"欢迎来到硅谷甄选后台",
            type:"success",
            position: 'bottom-right',
            duration:0
          })
        })

      }).catch(e=>{
    console.log(e)
    isLogining.value=false
    ElMessage({
      type:"error",
      message: e.msg,
      duration: 3000,
    })
  })




}

const ruleFormRef = ref()
const userPassRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'change',
    }
  ]
})

const determineFormRules=()=>{

  const loginType=loginRequest.loginType
  switch (loginType){
    case 'user_pass':return userPassRules
    case 'email_code':return []
    case 'mobile_code':return []
    default: return userPassRules
  }
}
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      doLogin()
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<script>
import UserPassItem from "@/views/Login/UserPassItem/index.vue";
import EmailCodeItem from "@/views/Login/EmailCodeItem/index.vue";
import MobileCodeItem from "@/views/Login/MobileCodeItem/index.vue";
export default {
  name: "LoginForm",
  components:{
    UserPassItem,
    EmailCodeItem,
    MobileCodeItem
  }
}
</script>


<style scoped>
.login-form {
  position: relative;
  top: 40vh;
  width: 80%;
  background: url("@/assets/images/login_form.png") no-repeat;
  background-size: cover;
  padding: 40px;

}

.login-form h1 {
  color: white;
  font-size: 40px;
}

.login-form h2 {
  color: white;
  font-size: 20px;
  margin: 20px 0;
}

.login-form .login-htn{
  width: 40%;
}

.login-form .login-type-htn{
  width: 30%;
}


.login-form .item-list {
  padding: 100px;
  padding-top: 40px;
  padding-bottom: 0;
}
</style>